/**
 * Created by aixin on 2018/12/11.
 */
import axios from 'axios';
import EventBus from '@/EventBus';
import HTTP_STATUS from '@/config/httpStatus';
import CONFIG from '@/config';

const request = axios.create({
    withCredentials: true,
    crossDomain: true,
    emuted: true
});

//  添加请求拦截器
request.interceptors.request.use(config => {
    config.headers.userId = sessionStorage.getItem('userid');
    config.headers.sysType = CONFIG.sysType;
    return config;
}, error => {
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(response => {
    const res = response.data;
    switch (response.data.code) {
    case HTTP_STATUS.SUCCESS:
        return Promise.resolve(res);
    case HTTP_STATUS.SESSION_OUT:
        EventBus.$emit('promptMessage', {
            message: res.message
        });
        return Promise.reject(response);
    default:
        EventBus.$emit('promptMessage', {
            message: res.message
        });
        return Promise.reject(response);
    }
}, (error) => {
    EventBus.$emit('promptMessage', {
        message: "网络开小差了..."
    });
    return Promise.reject(error);
});

export default request;
